package com.starblink.wishlist.wishboards.ui

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.apollographql.apollo3.api.Optional
import com.apollographql.apollo3.api.Query
import com.starblink.android.basic.base.BaseViewModel
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.basic.apollo.ext.optional
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.basic.util.log.YYLogUtils
import com.starblink.rocketreserver.*
import com.starblink.rocketreserver.type.CollectItem
import com.starblink.rocketreserver.type.GuessYouLikeProductByWishListParam
import com.starblink.rocketreserver.type.WishListsReq
import com.starblink.wishlist.wishallitems.ui.bean.RvTotalNumEntry
import com.starblink.wishlist.wishboards.ui.bean.*
import com.starblink.wishlist.wishlistdetails.ui.bean.RvBoardDetailsItemEntry
import kotlinx.coroutines.async
import kotlinx.coroutines.launch

class WishBoardsVM : BaseViewModel() {

    var mBoardsObserver: MutableLiveData<ArrayList<Any>> = MutableLiveData()

    var pageIndex = 1
    var guessPageIndex = 1
    var pageSize = 20
    var lastFeedsSize = 0

    var autoLoadMore = false

    var hasAddRelatedTitle = false

    var hasNext: Boolean? = null
    var guessLikeData: List<GuessYouLikeProductByWishListQuery.GuessYouLikeProductByWishList>? =
        null
    var currentPageIndex = 0

    /****************多选相关 ↓↓↓↓↓↓↓↓↓ ****************************/
    var choiceMode = false

    var selectAll = false
    var choiceNum = 0

    var recordIds = hashSetOf<String>()
    var record2Items = arrayListOf<RvBoardItemEntry>()

    /****************多选相关 ↑↑↑↑↑↑↑↑↑↑↑↑↑↑ ****************************/


    fun initSomeData() {
        if (mBoardsObserver.value == null) {
            mBoardsObserver.value = arrayListOf(RvNoBoardsEntry())
        }

    }


    inline fun initRefresh(showSimpleDialog: Boolean, crossinline hasFinish: () -> Unit) {

        autoLoadMore = false

        if (UserDataCenter.getAccountInfo()?.id == null) {
            mBoardsObserver.value!!.clear()
            mBoardsObserver.value!!.add(RvNoBoardsEntry())
            mBoardsObserver.postValue(mBoardsObserver.value)
            hasFinish()
            return
        }

        viewModelScope.launch {
            pageIndex = 1
            guessPageIndex = 1
            feedsPositionTag = 0
            val boards = async {
                return@async SkGqlClient.skQuery(
                    FetchWishListsByAccountIdV2Query(
                        wishListsReq = WishListsReq(
                            accountId = UserDataCenter.getAccountInfo()!!.id,
                            pageNo = pageIndex.optional(),
                            pageSize = pageSize.optional()
                        )
                    )
                    //fetchPolicy = FetchPolicy.NetworkFirst
                )?.data?.fetchWishListsByAccountIdV2
            }.await()
            //获取推荐
            val guessLike = async {
                return@async SkGqlClient.skQuery(
                    GuessYouLikeProductByWishListQuery(
                        params = GuessYouLikeProductByWishListParam(
                            pageNo = guessPageIndex,
                            pageSize = 20,
                            wishListId = Optional.present("0")
                        )
                    ),
                    //fetchPolicy = FetchPolicy.NetworkFirst
                    showFailToast = false,
                    showErrorToast = false
                )?.data?.guessYouLikeProductByWishList
            }.await()

            combineBoardsAndRelate(boards, guessLike, hasFinish = {
                hasFinish()
            })
        }
    }

    inline fun combineBoardsAndRelate(
        boards: FetchWishListsByAccountIdV2Query.FetchWishListsByAccountIdV2?,
        guessLike: List<GuessYouLikeProductByWishListQuery.GuessYouLikeProductByWishList>?,
        crossinline hasFinish: () -> Unit
    ) {
        hasNext = boards?.hasNext
        guessLikeData = guessLike
        mBoardsObserver.value!!.clear()
        hasAddRelatedTitle = false
        if (boards?.wishLists.isNullOrEmpty()) {
            mBoardsObserver.value!!.add(RvNoBoardsEntry())
        } else {
            mBoardsObserver.value!!.add(RvAddBoardsEntry())
            boards!!.wishLists!!.forEach {
                mBoardsObserver.value!!.add(
                    RvBoardItemEntry(
                        wishItem = it.wishListF,
                        showCheckMode = choiceMode,
//                                hasChoice = recordIds.contains(prdList.productF.id)
                        hasChoice = if (selectAll) true else (recordIds.contains(
                            it.wishListF.id
                        )),
                        position = mBoardsObserver.value!!.size
                    )
                )
            }
        }
        addGuessLike()
        mBoardsObserver.postValue(mBoardsObserver.value)
        hasFinish()
    }

    var feedsPositionTag = 0

    fun addGuessLike() {
        if (hasNext == false) {
            guessLikeData?.let {
                if (it.isNotEmpty()) {
                    mBoardsObserver.value!!.add(RvRelatedTitleEntry())
                    hasAddRelatedTitle = true
                    it.forEachIndexed { i, prd ->
                        mBoardsObserver.value!!.add(
                            RvBoardProductEntry(
                                position = i + feedsPositionTag,
                                product = prd.productF,
                                feedType = 3
                            )
                        )
                    }
                    feedsPositionTag = it.size
                    autoLoadMore = it.size > 3
                }
            }
        }
    }


    inline fun loadMore(crossinline hasFinish: () -> Unit) {
        if (hasNext == true) {
            viewModelScope.launch {
                pageIndex++
                var lastId: String? = null

                if (mBoardsObserver.value!!.isNotEmpty()) {
                    var it1 = mBoardsObserver.value!!.last()
                    if (it1 is RvBoardItemEntry) {
                        lastId = it1.wishItem.id
                    }
                }
                val boards = async {
                    return@async SkGqlClient.skQuery(
                        FetchWishListsByAccountIdV2Query(
                            wishListsReq = WishListsReq(
                                accountId = UserDataCenter.getAccountInfo()!!.id,
                                pageNo = pageIndex.optional(),
                                pageSize = pageSize.optional(),
                                lastId = lastId.optional()
                            )
                        ),
                        //fetchPolicy = FetchPolicy.NetworkFirst
                    )?.data?.fetchWishListsByAccountIdV2
                }.await()
                hasNext = boards?.hasNext
                boards!!.wishLists!!.forEach {
                    mBoardsObserver.value!!.add(
                        RvBoardItemEntry(
                            wishItem = it.wishListF,
                            showCheckMode = choiceMode,
//                                hasChoice = recordIds.contains(prdList.productF.id)
                            hasChoice = if (selectAll) true else (recordIds.contains(
                                it.wishListF.id
                            )),
                            position = mBoardsObserver.value!!.size
                        )
                    )
                }
                addGuessLike()
                mBoardsObserver.postValue(mBoardsObserver.value)
                hasFinish()
            }
        } else {
            viewModelScope.launch {
                guessPageIndex++
                val moreRelated = SkGqlClient.skQuery(
                    GuessYouLikeProductByWishListQuery(
                        params = GuessYouLikeProductByWishListParam(
                            pageNo = guessPageIndex,
                            pageSize = 20,
                            wishListId = Optional.present("0")
                        )
                    ),
                    //fetchPolicy = FetchPolicy.NetworkFirst
                    showFailToast = false,
                    showErrorToast = false
                )?.data?.guessYouLikeProductByWishList
                if (!moreRelated.isNullOrEmpty()) {
                    if (!hasAddRelatedTitle) {
                        mBoardsObserver.value!!.add(RvRelatedTitleEntry())
                        hasAddRelatedTitle = true
                    }
                    moreRelated.forEachIndexed { i, prd ->
                        mBoardsObserver.value!!.add(
                            RvBoardProductEntry(
                                position = feedsPositionTag + i,
                                product = prd.productF,
                                feedType = 3
                            )
                        )
                    }
                    feedsPositionTag += moreRelated.size
                    mBoardsObserver.postValue(mBoardsObserver.value)
                    hasFinish()
                } else {
                    guessPageIndex--
                    hasFinish()
                }
            }
        }


    }


    //批量删除收藏夹
    fun deleteCollItems() {
        viewModelScope.launch {
            var items = arrayListOf<Long>()
            record2Items.forEach { prdF ->
                items.add(
                    prdF.wishItem.id.toLong()
                )
            }
            var result = SkGqlClient.skMutation(
                DeleteWishListV2Mutation(
                    wishListIds = items
                ),
                showDefaultLoading = true
            )?.data?.deleteWishListV2

            if (result == true) {
                //这里的下标不能取0 因为用户插入是无序的 要用需要排序一次  取最小值 但是因为要刷总数 所以这里暂时用不到
//                val startIndex = record2Items[0].position
                record2Items.forEach { prdF ->
                    mBoardsObserver.value?.remove(prdF)
                }
                record2Items.clear()
                recordIds.clear()
                mBoardsObserver.postValue(mBoardsObserver.value)
                FlowBus.with<Int>(FlowConst.WISH_BOARDS_SHOW_TOAST)
                    .post(0)
                YYLogUtils.e(" #######startIndex22   ${0}")
            }
        }
    }


    //单独删除
    inline fun deleteCollItem(
        model: RvBoardItemEntry,
        position: Int,
        crossinline hasFinish: () -> Unit
    ) {
        viewModelScope.launch {
            var result = SkGqlClient.skMutation(
                DeleteWishListMutation(
                    wishListId = model.wishItem.id
                ),
                showDefaultLoading = true
            )?.data?.deleteWishList

            if (result == true) {
                hasFinish()
                FlowBus.with<Int>(FlowConst.WISH_BOARDS_SHOW_TOAST)
                    .post(0)
            }
        }
    }


    /**
     * 刷新底部选项 同时记录选中数据
     */
    fun refreshChoiceNum(): Int {
//        if (allCheck) {
//            choiceNum = mAllItemsObserver.value!!.size
//            return choiceNum
//        }
        var num = 0
        recordIds.clear()
        record2Items.clear()
        mBoardsObserver.value?.forEach {
            if (it is RvBoardItemEntry && it.hasChoice) {
                num++
                it.wishItem.id?.let { prdId ->
                    recordIds.add(prdId)
                    record2Items.add(it)
                }
            }
        }
        choiceNum = num
        return choiceNum
    }

    fun clearChoiceHistory() {
        selectAll = false
        recordIds.clear()
        record2Items.clear()
        choiceNum = 0
    }

    fun getCurrentItemDataSize(): Int {
        var num = 0
        mBoardsObserver.value?.forEach {
            if (it is RvBoardItemEntry) {
                num++
            }
        }
        return num
    }
}
